<template>
  <div class="question-container">
    <h2>原始问题详情</h2>
    <div class="tab-header">
      <button 
        class="tab-button" 
        :class="{ active: activeTab === 'original' }"
        @click="activeTab = 'original'"
      >
        原始问题
      </button>
      <button 
        class="tab-button" 
        :class="{ active: activeTab === 'standard' }"
        @click="activeTab = 'standard'"
      >
        标准问题
      </button>
    </div>

    <div class="tab-content">
      <div v-if="activeTab === 'original' && originalQuestion" class="original-question">
        <div class="meta-info">
          <span><strong>ID:</strong> {{ originalQuestion.id }}</span>
          <span><strong>更新时间:</strong> {{ originalQuestion.updateTime }}</span>
        </div>
        <div class="detail-item">
          <label>标题：</label>
          <span>{{ originalQuestion.title }}</span>
        </div>
        <div class="detail-item">
          <label>版本：</label>
          <span>{{ originalQuestion.version }}</span>
        </div>
        <div class="detail-item">
          <label>内容：</label>
          <p>{{ originalQuestion.content }}</p>
        </div>
        <div class="actions">
          <!-- <button @click="editQuestion" class="edit-btn">编辑(TODO)</button> -->
          <button 
            @click="deleteQuestion" 
            class="delete-btn"
            :disabled="versionStore.currentVersion?.published"
          >
            删除(TODO)
          </button>
          <button 
            @click="showCreateStandard = !showCreateStandard" 
            class="create-btn"
            :disabled="versionStore.currentVersion?.published"
          >
            {{ showCreateStandard ? '取消' : '创建标准问题' }}
          </button>
          <div v-if="versionStore.currentVersion?.published" class="disabled-hint">
            当前版本已发布，不可修改
          </div>
        </div>

        <div v-if="showCreateStandard" class="create-standard-form">
          <div class="form-group">
            <label for="standardQuestion">标准问题内容</label>
            <textarea 
              id="standardQuestion" 
              v-model="standardQuestionContent" 
              placeholder="请输入标准问题内容"
              rows="3"
            ></textarea>
          </div>
          <button 
            @click="createStandard" 
            :disabled="!standardQuestionContent" 
            class="submit-btn"
          >
            提交
          </button>
        </div>
      </div>

      <div v-if="activeTab === 'standard'" class="standard-questions">
        <div v-if="standardQA.length > 0">
          <ul>
            <li v-for="qa in standardQA" :key="qa.question.id">
              <div class="standard-question" @click="goToStandardDetail(qa.question)">
                <div class="meta-info">
                  <span><strong>ID:</strong> {{ qa.question.id }}</span>
                  <span><strong>更新时间:</strong> {{ qa.question.updateTime }}</span>
                </div>
                <p><strong>标准问题：</strong>{{ qa.question.question }}</p>
                <p><strong>状态：</strong>{{ qa.question.active ? '活跃' : '非活跃' }}</p>
              </div>
              <div class="answer-container">
                <strong>标准答案：</strong>
                <div class="answer-content">{{ qa.answer?.answer || '暂无标准答案' }}</div>
              </div>
            </li>
          </ul>
        </div>
        <div v-else-if="loading" class="loading">加载中...</div>
        <div v-else class="no-data">暂无标准问题</div>
      </div>
    </div>
    <div v-if="showToast" :class="['toast', toastType]">
      {{ toastMessage }}
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useVersionStore } from '@/stores/versionStore'

import { 
  type OriginalQuestion,
  type StandardQuestion,
  getStandardByOriginal,
  createStandardQuestion
} from '@/api/question'
import { getStandardAnswersByQuestionId, type StandardAnswer } from '@/api/answer'


interface Props {
  id: number
  version: string
  title: string
  content: string
  source: string
  updateTime: string
  active: boolean
}

interface StandardQA{
  question: StandardQuestion,
  answer: StandardAnswer | undefined
}

export default defineComponent({
  name: 'QuestionDetail',
  props: {
    id: {
      type: Number,
      required: true
    },
    version: {
      type: String,
      default: 'v1.0'
    },
    title: {
      type: String,
      default: ''
    },
    content: {
      type: String,
      default: ''
    },
    source: {
      type: String,
      default: ''
    },
    updateTime: {
      type: String,
      default: ''
    },
    active: {
      type: Boolean,
      default: true
    }
  },
  setup(props: Props) {
    const router = useRouter()
    const versionStore = useVersionStore()
    const safeDecodeURI = (str: string) => {
      try {
        return decodeURIComponent(str)
      } catch (e) {
        console.warn('URI解码失败:', e)
        return str
      }
    }

    const originalQuestion = ref<OriginalQuestion>({
      id: props.id,
      version: versionStore.currentVersion?.ver_code || props.version,
      title: props.title ? safeDecodeURI(props.title) : '',
      content: props.content ? safeDecodeURI(props.content) : '',
      source: props.source,
      updateTime: props.updateTime,
      active: props.active
    })

    const goToStandardDetail = (question: StandardQuestion) => {
      if (!question.id || !props.id) {
        console.error('缺少必要的路由参数')
        return
      }
      
      router.push({
        name: 'standardDetail',
        params: {
          id: String(question.id),
          originalId: String(props.id),
          version: versionStore.currentVersion?.ver_code || question.originalQuestion?.version || 'v1.0'
        }
      })
    }
    const standardQA = ref<StandardQA[]>([])
    const loading = ref(false)

    const loadData = async () => {
      loading.value = true
      try {
        // 获取标准问题列表
        const questions = await getStandardByOriginal(props.id, props.version)
        
        // 为每个问题获取标准答案
        standardQA.value = await Promise.all(questions.map(async (q) => {
          try {
            const answer = await getStandardAnswersByQuestionId(q.id, versionStore.currentVersion?.ver_code || 'unknown')
            console.log(`获取问题${q.id}的标准答案成功:`, answer)
            return {
              question: q,
              answer: answer
            }
          } catch (error) {
            console.error(`获取问题${q.id}的标准答案失败:`, error)
            return {
              question: q,
              answer: undefined
            }
          }
        }))
      } catch (error) {
        console.error('加载标准问题失败:', error)
      } finally {
        loading.value = false
      }
    }

    const activeTab = ref<'original' | 'standard'>('original')
    const showToast = ref(false)
    const toastMessage = ref('')
    const toastType = ref<'success'|'error'|'warning'>('success')
    const showCreateStandard = ref(false)
    const standardQuestionContent = ref('')

    const createStandard = async () => {
      if (!standardQuestionContent.value) {
        showToast.value = true
        toastMessage.value = '请输入标准问题内容'
        toastType.value = 'warning'
        setTimeout(() => { showToast.value = false }, 2000)
        return
      }
      
      try {
        await createStandardQuestion(
          standardQuestionContent.value,
          props.id,
          versionStore.currentVersion?.ver_code || props.version
        )
        
        showToast.value = true
        toastMessage.value = '标准问题创建成功'
        toastType.value = 'success'
        setTimeout(() => { showToast.value = false }, 2000)
        showCreateStandard.value = false
        standardQuestionContent.value = ''
        // 刷新标准问题列表
        await loadData()
      } catch (error) {
        // console.error('创建标准问题失败:', error)
        showToast.value = true
        toastMessage.value = '创建失败，请重试'
        toastType.value = 'error'
        setTimeout(() => { showToast.value = false }, 2000)
      }
    }

    const editQuestion = () => {
      // TODO: 实现编辑功能
      console.log('编辑问题')
    }

    const deleteQuestion = () => {
      // TODO: 实现删除功能
      console.log('删除问题')
    }

    onMounted(() => {
      loadData()
    })

    return {
      activeTab,
      originalQuestion,
      standardQA,
      loading,
      showCreateStandard,
      standardQuestionContent,
      editQuestion,
      deleteQuestion,
      createStandard,
      goToStandardDetail,
      showToast,
      toastMessage,
      toastType,
      versionStore
    }
  }
})
</script>

<style scoped>
.question-container {
  padding: 16px 5%;
  width: 90%;
  text-align: left;
}

.tab-header {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #e1e4e8;
}

.tab-button {
  padding: 12px 24px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  color: #666;
  position: relative;
  transition: all 0.3s ease;
}

.tab-button:hover {
  color: #1890ff;
}

.tab-button.active {
  color: #1890ff;
  font-weight: 600;
}

.tab-button.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #1890ff;
}

.tab-content {
  padding: 16px 0;
}

@media (max-width: 768px) {
  .question-container {
    padding: 16px;
    width: calc(100% - 32px);
  }
  
  .tab-button {
    padding: 10px 16px;
    font-size: 14px;
  }
  
  .actions {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .actions button {
    margin-right: 0;
    flex: 1 0 auto;
    min-width: 120px;
  }
}

.detail-item {
  margin: 10px 0;
  text-align: left;
}

.detail-item label {
  font-weight: bold;
}

.meta-info {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  font-size: 14px;
  color: #666;
}

.meta-info span {
  display: flex;
  align-items: center;
}

.meta-info strong {
  margin-right: 5px;
  color: #333;
}

.actions {
  margin: 20px 0;
  text-align: left;
}

button {
  padding: 8px 16px;
  margin-right: 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.edit-btn {
  background-color: #42b983;
  color: white;
}

.delete-btn {
  background-color: #f56c6c;
  color: white;
}

.delete-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.create-btn {
  background-color: #1890ff;
  color: white;
}

.create-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.disabled-hint {
  color: #666;
  font-size: 12px;
  margin-top: 8px;
}

.create-standard-form {
  margin-top: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e1e4e8;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
}

.submit-btn {
  background-color: #42b983;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}


.standard-question {
  margin: 16px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e1e4e8;
  cursor: pointer;
  transition: all 0.2s ease;
}

.standard-question:hover {
  background: #e6f7ff;
  border-color: #1890ff;
}

.standard-question:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.standard-question p {
  margin: 8px 0;
  line-height: 1.6;
  font-size: 15px;
  text-align: left;
}

.standard-question p strong {
  color: #24292e;
  font-weight: 600;
  margin-right: 8px;
}

.standard-question p:first-child {
  margin-top: 0;
}

.standard-question p:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.standard-questions {
  flex: 1 1 38%;
  min-width: 300px;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  text-align: left;
}

.standard-questions h2 {
  font-size: 1.5rem;
  color: #2c3e50;
  margin: 0 0 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.answer-container {
  margin: 12px 0;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #42b983;
  font-size: 15px;
}

.answer-content {
  margin-top: 8px;
  white-space: pre-wrap;
  line-height: 1.6;
  font-size: 15px;
}

.loading, .no-data {
  text-align: center;
  margin: 20px 0;
  color: #666;
}

.toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 8px 16px;
  color: white;
  border-radius: 4px;
  z-index: 9999;
  animation: fadeInOut 2s ease-in-out;
}

.toast.success {
  background-color: #42b983;
}

.toast.error {
  background-color: #f56c6c;
}

.toast.warning {
  background-color: #e6a23c;
}

@keyframes fadeInOut {
  0% { opacity: 0; transform: translateX(-50%) translateY(-20px); }
  10% { opacity: 1; transform: translateX(-50%) translateY(0); }
  90% { opacity: 1; transform: translateX(-50%) translateY(0); }
  100% { opacity: 0; transform: translateX(-50%) translateY(-20px); }
}
</style>
